package com.umpay.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimeUtil {

    private static SimpleDateFormat yyyyDf = new SimpleDateFormat("yyyy");
    private static final SimpleDateFormat fmtMonth4 = new SimpleDateFormat("yyMM");
    
    public static String date(String fmt) {
        return new SimpleDateFormat(fmt).format(new Date());
    }

    public static String date(String fmt, long t) {
        return new SimpleDateFormat(fmt).format(new Date(t));
    }

    public static String date8() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    public static String date8(Date date) {
        return new SimpleDateFormat("yyyyMMdd").format(date);
    }

    public static String time6() {
        return new SimpleDateFormat("HHmmss").format(new Date());
    }

    public static String time6(Date date) {
        return new SimpleDateFormat("HHmmss").format(date);
    }

    public static String datetime14() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    public static String datetime14(Date date) {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
    }

    public static String datetime14(long t) {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(t));
    }

    public static String calcMonth(String month6, int m) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(month6.substring(0, 4)), Integer.parseInt(month6.substring(4, 6)) - 1, 1);
        cal.add(Calendar.MONTH, m);
        return new SimpleDateFormat("yyyyMM").format(cal.getTime());
    }

    public static String calcDay(String day8, int d) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        cal.add(Calendar.DATE, d);
        return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
    }

    public static String calcSecond(String time14, int s) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(time14.substring(0, 4)), Integer.parseInt(time14.substring(4, 6)) - 1,
                Integer.parseInt(time14.substring(6, 8)), Integer.parseInt(time14.substring(8, 10)),
                Integer.parseInt(time14.substring(10, 12)), Integer.parseInt(time14.substring(12, 14)));
        cal.add(Calendar.SECOND, s);
        return new SimpleDateFormat("yyyyMMddHHmmss").format(cal.getTime());
    }
    
    public static String calcMonth4(String month6, int m)
    {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(month6.substring(2, 4)), Integer.parseInt(month6.substring(4, 6)) - 1 + m, 1);
        synchronized (fmtMonth4)
        {
            return fmtMonth4.format(cal.getTime());
        }
    }
    
    public static long toMilliSec(String time14) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(time14.substring(0, 4)), Integer.parseInt(time14.substring(4, 6)) - 1,
                Integer.parseInt(time14.substring(6, 8)), Integer.parseInt(time14.substring(8, 10)),
                Integer.parseInt(time14.substring(10, 12)), Integer.parseInt(time14.substring(12, 14)));
        return cal.getTimeInMillis();
    }

    public static int getActualMaximum(String day8, int field) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        return cal.getActualMaximum(field);
    }

    public static int getActualMinimum(String day8, int field) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        return cal.getActualMinimum(field);
    }

    /**
     * 得到系统时间年份
     * 
     * @return
     */
    public static String getDateYear() {
        return yyyyDf.format(new Date());
    }

    /**
     * 处理银行的checkDate没有年份的情冄1�7
     * 
     * @param v
     * @return
     */
    public static String formatBankCheckDate(String v) {
        if (v.length() == 4) {
            String yyyy = getDateYear();
            String stldate = yyyy + v;
            try {
                SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");

                long slttime = fmt.parse(stldate).getTime();

                long currtime = System.currentTimeMillis();

                long dis = slttime - currtime;

                long day1 = 24 * 3600 * 1000;

                if (Math.abs(dis) >= day1) {

                    if (slttime < currtime) {

                        yyyy = String.valueOf(Integer.parseInt(yyyy) + 1);

                        stldate = yyyy + v;

                    } else {

                        yyyy = String.valueOf(Integer.parseInt(yyyy) - 1);

                        stldate = yyyy + v;

                    }

                }

                return stldate;
            } catch (Exception e) {

            }
        }
        return v;

    }

    /**
     * String
     * 
     * @param time
     * @return
     */
    public static String parseTimestampToDStr(Timestamp time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        formatter.format(time);
        return formatter.format(time);
    }

    /**
     * String
     * 
     * @param time
     * @return
     */
    public static String parseTimestampToTStr(Timestamp time) {
        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        formatter.format(time);
        return formatter.format(time);
    }

    public static String formatDateTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * description: 在now基础上增加amount个日
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Date addDay(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.DATE, amount);
        return cal.getTime();
    }
    
	/**
	 * 
	 * description: 在now基础上增加amount个日
	 * @param endDate
	 * @param amount
	 * @return
	 */
	public static String addDay(String now, int amount) {
		Date d ;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		try {
			sf.setLenient(false);
			d = sf.parse(now);
		} catch (Exception e) {
			d = new Date();
		}
		return sf.format(addDay(d, amount));
	}

    /**
     * description: 在now基础上增加amount个月
     * 
     * @param now
     * @param amount
     * @return
     */
    public static Date addMonth(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MONTH, amount);
        return cal.getTime();
    }

    /**
     * description: 在now基础上增加amount个年
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Date addYear(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.YEAR, amount);
        return cal.getTime();
    }
    
	/**
	 * 
	 * description: 在now基础上增加amount个年
	 * @param endDate
	 * @param amount
	 * @return
	 */
	public static String addYear(String now, int amount) {
		Date d ;
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		try {
			sf.setLenient(false);
			d = sf.parse(now);
		} catch (Exception e) {
			d = new Date();
		}
		return sf.format(addYear(d, amount));
	}

    /**
     * description: 在now基础上增加amount个分钟
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Timestamp addMin(Timestamp now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MINUTE, amount);
        return new Timestamp(cal.getTime().getTime());
    }

    /**
     * 格式化日期为制定字符串
     * 
     * @param date
     * @param format
     * @return
     */
    public static String foramtDate2String(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 将日期格式的字符串转换为日期
     * 
     * @param dateStr
     *            源日期字符串
     * @param formatStr
     *            源日期字符串格式
     */
    public static Date formatStringToDate(String dateStr, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        try {
            return format.parse(dateStr);
        } catch (Exception ex) {
            RuntimeException rex = new RuntimeException(ex.getMessage());
            rex.setStackTrace(ex.getStackTrace());
            throw rex;
        }
    }

    /**
     * description: 判断当前时间是否为19点以后
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static boolean nowIsNight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int i = cal.get(Calendar.HOUR_OF_DAY);
        return i > 18;
    }

    /**
     * 获取数据库日期,如果获取失败则取系统当前日期 * @param format日期格式化字符串
     * 
     * @return
     */
    public static String getDbTime(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Timestamp dbTime = null;
        String currTime = "";
        // try {
        // CommonDao commonDao = DaoFactory.getCommonDao();
        // dbTime = commonDao.getCurrentDBTime();
        // } catch (Exception e) {
        // dbTime = new Timestamp(System.currentTimeMillis());
        // }
        // if(dbTime == null){
        dbTime = new Timestamp(System.currentTimeMillis());
        // }
        currTime = formatter.format(dbTime);
        return currTime;
    }

    /**
     * 校验交易日期是否小于当前数据库日期指定天数
     * 
     * @param trace
     * @param day
     * @return
     */
    public static boolean checkTransDateByTrace(String trace, int day) {
        String traceDate = trace.substring(0, 6);
        return checkTransDate(traceDate, day, "yyMMdd");
    }

    /**
     * 校验日期是否小于当前数据库日期的指定天数
     * 
     * @param datestr
     *            需要验证的日期
     * @param day
     *            指定天数
     * @param patt
     *            日期格式,例:yyyyMMdd
     * @return
     */
    public static boolean checkTransDate(String datestr, int day, String patt) {
        SimpleDateFormat format = new SimpleDateFormat(patt);
        try {
            Date date = format.parse(datestr);
            Date dbDate = format.parse(getDbTime(patt));
            return addDay(date, day).getTime() < dbDate.getTime();
        } catch (ParseException e) {
            return false;
        }
    }
    
    /**
     * 
     * @Title: getExpireTime  
     * @Description: 设置订单过期时间，以分钟为单位  
     * @param @param expireTime
     * @param @return    参数  
     * @return Timestamp    返回类型  
     * @throws
     */
    public static Timestamp getExpireTime(String expireTime){
    	long expire = 0;
    	if (StringUtils.isNotEmpty(expireTime)){
            expire = Long.valueOf(StringUtils.trim(expireTime)) * 60;// 将请求的分钟转换为秒
        }
    	if (expire == 0){   // 如果没有取得过期时间使用秒为单位的一天
            expire = 86400; // 60*60*24;
        }
    	Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, Integer.valueOf(String.valueOf(expire)));
        Timestamp expiretime = new Timestamp(cal.getTime().getTime());
        return expiretime;
    }
    
    public static Timestamp getCurrentTime(){
	    Date date = new Date();       
	    Timestamp time = new Timestamp(date.getTime());
		return time;
    }
    
    public static void main(String[] args) {
    	System.out.println(getCurrentTime());
	}
    
    /**
     * 验证日期是否合法
     * @param date
     * @return
     */
    public static boolean validDate(String date) {

		Date now = new Date();
		String yestoday = TimeUtil.foramtDate2String(TimeUtil.addDay(now, -1),"yyyyMMdd");
		String today = TimeUtil.date8(now);
		String tomorrow = today;
		if (TimeUtil.nowIsNight()) {
			tomorrow = TimeUtil.foramtDate2String(TimeUtil.addDay(now, 1),"yyyyMMdd");
		}
		if (!yestoday.equals(date) && !today.equals(date)&& !tomorrow.equals(date)) {
			
			return false;
		}
		return true;
	}
    
	/**
	 * 获取两日期之间的年月
	 * @param startDate
	 * @param endDate
	 * @return
	 * @throws ParseException 
	 */
	public static List<String> getYearAndMonth(String startDate, String endDate) throws ParseException {
		List<String> list = new ArrayList<String>();
		String temp = startDate;
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		do {
			list.add(temp.substring(2, 6));
			Date tempDate = format.parse(temp);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(tempDate);
			calendar.add(Calendar.MONTH, 1);
			temp = format.format(calendar.getTime());			
		} while ((temp.substring(0, 6)).compareTo(endDate.substring(0, 6)) <= 0);
		return list;
	}
    
}
